package com.example.lhsama.controller;

import com.example.lhsama.domain.Product;
import com.example.lhsama.service.ProductService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/product")
public class ProductController {
    SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
    @Autowired
    private ProductService productService;


    static String realPath = "D:\\cache\\";

    @RequestMapping("/list")
    public String productList(Model model){
        List<Product> productList = productService.list();
        model.addAttribute("products",productList);
        return "/pages/productList";
    }


    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable Integer id){
        Product product = productService.getById(id);
        if(product.getImg()!=null){
            String path = product.getImg().replace("/","\\").replace("\\image",realPath);
            File file = new File(path);

            boolean flag = file.delete();
            System.out.println((flag?"图片删除成功":"图片删除失败")+file.getPath());
        }
        productService.removeById(id);
        return "redirect:/product/list";
    }

    @GetMapping("/update/{id}")
    public String UpdatePage(@PathVariable Integer id,Model model){
        Product product = productService.getById(id);
        model.addAttribute("product",product);
        return "/pages/productUpdate";
    }
    @GetMapping("/insert")
    public String UpdatePage(){

        return "/pages/productInsert";
    }

    /**
     * 将product对象和图片上传上来，图片保存本地，可移到nginx文件服务器
     * @param product
     * @param uploadFile
     * @param req
     * @return
     * @throws IOException
     */
    @PostMapping("/save")
    public String save(Product product, @RequestPart("productImg") MultipartFile uploadFile, HttpServletRequest req) throws IOException {
        if (!uploadFile.isEmpty()) {
            String format = sd.format(new Date());
            String oldName = uploadFile.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."), oldName.length());

//        String path = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
//        String realPath = path.replace('/', '\\').substring(1,path.length());
//        String realPath = this.getClass().getClassLoader().getResource("static/upload").getFile();
            //  /image/2021/09/23/21c632b3-b24c-4ef2-8ef3-679c9aed8ac3.jpg
            //用于查看路径是否正确
            System.out.println(realPath);


            File file = new File(realPath + "\\" + format);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            try {
                uploadFile.transferTo(new File(file, newName));
                //String path01 = "../upload/"+newName;
                product.setImg("/image/" + format + "/" + newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (product.getProductNum() == null)
        product.setProductNum(UUID.randomUUID().toString().replace("-", ""));
        System.out.println(product);

        if (product.getId()==null)
        productService.save(product);
        else
            productService.updateById(product);
        return "redirect:/product/list";
    }


}
